Working with Strings - Part 1

© 2005, Brad Moore

LB Connection

Home

Save As w/o Save

Working with Strings

Stylebits Corner

Eddie's Lessons, v8

Multiple Languages

Speech for Disabled

File Searcher

Newsletter help

Index


Introduction

One of the finer arts of programming is string manipulation. Liberty Basic is fairly (although not exceedingly) rich in string functions. What is missing can easily be built from existing functions. Liberty Basic provides the following string functions:

ASC(s$) - eturns the ASCII value of the first character of string s$

CHR$( n ) - returns a one character long string represented by the ASCII value n.

INSTR(string1, string2, starting) - returns the position of string2 within string1

LEN( string ) - returns the length in characters of string.

LEFT$(string, number) - returns from string the specified number of characters starting from the left.

RIGHT$(string, number) - returns a sequence of characters from the right hand side of string using number to determine how many characters to return

MID$(string, index, [number]) - extracts a sequence of characters from the string starting at index. [number] is optional but if specified will extract only as many characters as number specifies, starting from index.

LOWER$( string ) - returns a copy of the contents of string, but with all letters converted to lowercase.

UPPER$( string ) - returns a copy of the contents of string, but with all letters converted to uppercase.

TRIM$( string ) - removes any spaces from the start and end of string.

SPACE$( n ) - will a return a string of n space characters (ASCII 32).

WORD$( stringExpression, n [,string delimiter] ) - returns the nth word (as defined by the space character or the optional string delimiter) in the string stringExpression.

For more detailed information on the string functions please see the Liberty Basic Helpfile.

Using the function above we can easily manipulate a string. In the example below several of the string functions are used to replace one word in a string with another word:


a$ = "This is the time for all good men..."
b$ = "time"
c$ = "place"

print "Original string = ";a$
print "String to replace = ";b$
print "String to insert = ";c$

'I want to replace the word "time" with "place"
'first find the string...

pos = instr(a$, b$)

'now store the portion of the string before the word "time"

l$ = left$(a$, pos-1)

'now get the portion of the string after the word "time"

r$ = mid$(a$, pos+len(b$))

'lets see what we have:

print "Location of string to remove (beginning) = ";pos
print "The left fragment = ";l$
print "The right fragment = ";r$

'now put it all together, subing "place" for time

final$ = l$ + c$ + r$

print "The final string = ";final$

This can be modified to create our own string replacement function that we can reuse when ever we need such a function:


function replaceStr$(original$, toReplace$, replacement$)
    'this function will locate the toReplace$ in the original$ and
    'replace it with the replacement$ returning the new string.
    'if the toReplace$ is not located the original string is returned.
    'The replacement$ can be of zero length (removing the toReplace$)

    final$ = original$

    if len(original$) > 0 and len(toReplace$) > 0 then
        'first find the toReplace string...
        pos = instr(original$, toReplace$)

        if pos > 0 then
            'now store the portion of the string before the toReplace string
            l$ = left$(original$, pos-1)

            'now get the portion of the string after the word "time"
            r$ = mid$(original$, pos+len(toReplace$))

            'now put it all together, subing "place" for time
            final$ = l$ + replacement$ + r$
        end if
    end if

    replaceStr$ = final$

end function

We can exercise the function with the following code:


a$ = "This is the time for all good men..."
b$ = "time"
c$ = "place"

print "Original string = ";a$
print "New string = ";replaceStr$(a$, b$, c$)

a$ = "The quick brown fox jumped over the silly blue dog"
b$ = "time"
c$ = "place"

print "Original string = ";a$
print "New string = ";replaceStr$(a$, b$, c$)

b$ = "blue"
c$ = "brown"

print "Original string = ";a$
print "New string = ";replaceStr$(a$, b$, c$)

b$ = "quick brown "
c$ = ""

print "Original string = ";a$
print "New string = ";replaceStr$(a$, b$, c$)
end

function replaceStr$(original$, toReplace$, replacement$)
    'this function will locate the toReplace$ in the original$ and
    'replace it with the replacement$ returning the new string.
    'if the toReplace$ is not located the original string is returned.
    'The replacement$ can be of zero length (removing the toReplace$)

    final$ = original$

    if len(original$) > 0 and len(toReplace$) > 0 then
        'first find the toReplace string...
        pos = instr(original$, toReplace$)

        if pos > 0 then
            'now store the portion of the string before the toReplace string
            l$ = left$(original$, pos-1)

            'now get the portion of the string after the word "time"
            r$ = mid$(original$, pos+len(toReplace$))

            'now put it all together, subing "place" for time
            final$ = l$ + replacement$ + r$
        end if
    end if

    replaceStr$ = final$

end function

Changing tracks a little, I really love the WORD$ function. It simplifies the process parsing strings. Parsing is the act of breaking a string into several smaller parts to act on it. We did that in the function above using the INSTR$ function in conjunction with the LEFT$ and MID$ functions. Typically strings are parsed by separating them into individual words at the white spaces between words and discarding the white spaces.

WORD$ makes life easier by letting the programmer focus on the result rather than the method of parsing the string. You specify what word you want from the given string and what character you want to be the separator (by default this is the space). If you want all the words you simply do a FOR-NEXT loop and spin through the whole string getting word number one, then word number two, then word number three and so on. Quick and easy - except, how do you know how many total words there are based on your delimiter?

What is needed is a WORDCOUNT function. This is pretty easy to implement using the WORD$ function:


 function wordcount(cnt$, delimiter$)
    'returns the number of words in the string
    '  as would be returned by the word$ function
    '  using the given delimeter
 
    cnt = 0
    work$ = ""
 
    while len(work$) < len(cnt$)
        cnt = cnt + 1
        work$ = work$ + word$(cnt$,cnt,delimiter$) + delimiter$
    wend
 
    wordcount = cnt
 
 end function

This type of function can be a little complex to understand. What is happening here is we are passed the original string (cnt$). In the function we rebuild the original string in a temporary string (work$) one word at a time. Each time we go through the WHILE loop we add another word from the original (cnt$) string to the temporary string (work$) along with a delimiter. We continue to loop, adding to our temporary string until the length of the temporary string is equal to (or greater) than the original string. Each time through the WHILE loop we are counting the iteration. In fact the counter is used for double duty, as it is the index into the original string to get the next word to add to the temporary string. In the end we will have the total number of words in the string.

As I described earlier this is useful for working with the string further for parsing the string. Take this example which exercises the wordcount function:


a$ = "John David|Peter Sam Fred"

 print "There are ";wordcount(a$, "|");" words"
 for x = 1 to wordcount(a$, "|")
    print x;") ";word$(a$, x, "|")
 next x

 print "There are ";wordcount(a$, "/");" words"
 for x = 1 to wordcount(a$, "/")
    print x;") ";word$(a$, x, "/")
 next x

 print "There are ";wordcount(a$, " ");" words"
 for x = 1 to wordcount(a$, " ")
    print x;") ";word$(a$, x, " ")
 next x


 function wordcount(cnt$, delimiter$)
    'returns the number of words in the string
    '  as would be returned by the word$ function
    '  using the given delimeter
 
    cnt = 0
    work$ = ""
 
    while len(work$) < len(cnt$)
        cnt = cnt + 1
        work$ = work$ + word$(cnt$,cnt,delimiter$) + delimiter$
    wend
 
    wordcount = cnt
 
 end function

As you can see the WORDCOUNT function simplifies the process of parsing the string. We can also use it for some fancy computing to extract the path and filename from a fully qualified path. This has to be one of my all time favorite code snippets:


 path$ = "c:\files\data\projects\mycoolprj.dat"
 filename$=word$(path$,wordcount(path$,"\"), "\")
 fpath$ = word$(path$,1,filename$)

 print "Full path = ";path$
 print "Filename = ";filename$
 print "File path = ";fpath$

 end 

 function wordcount(cnt$, delimiter$)
    'returns the number of words in the string
    '  as would be returned by the word$ function
    '  using the given delimeter
 
    cnt = 0
    work$ = ""
 
    while len(work$) < len(cnt$)
        cnt = cnt + 1
        work$ = work$ + word$(cnt$,cnt,delimiter$) + delimiter$
    wend
 
    wordcount = cnt
 
 end function

This is really fun as it uses both the word$ and wordcount functions together to get the filename. wordcount(path$,"\") is returning the total number of words in the string with the delimiter "\". In the case of the example it is five (four delimiters). We know the fifth word is the filename, so we use that value in the word$ function with the same delimiter to get the filename.

By using the filename as the delimiter in the next line of code and extracting the first (and only) word using the WORD$ function again we get the directory path.

Now you have two new string functions for your arsenal of reusable code. Have fun.


Home

Save As w/o Save

Working with Strings

Stylebits Corner

Eddie's Lessons, v8

Multiple Languages

Speech for Disabled

File Searcher

Newsletter help

Index